from pyramid.response import Response
from pyramid.view import view_config

from sqlalchemy.exc import DBAPIError
from docutils.core import publish_parts

from pyramid.httpexceptions import HTTPNotFound,HTTPFound

from .models import (
    DBSession,
    Page,
    )

import re

namePattern=re.compile('\[\[\[(?P<pagename>\w+)\]\]\]')


@view_config(route_name='home')
def home(request):
    return HTTPFound(location=request.route_url('viewPage',pagename='FrontPage'))

@view_config(route_name='viewPage', renderer='templates/viewPage.mako')
def viewPage(request):
   name=request.matchdict['pagename']
   page=DBSession.query(Page).filter_by(name=name).first()

   if not page:
       return HTTPNotFound('Page Not Found')

   def name2link(match):
       pagename=match.groupdict()['pagename']
       exits=DBSession.query(Page).filter_by(name=pagename).all()

       method='viewPage' if exits else 'addPage'

       return '<a href="{}">{}</a>'.format(
               request.route_url(method,pagename=pagename),
               pagename,
               )
   
   content=publish_parts(page.data,writer_name='html')['html_body']
   content=namePattern.sub(name2link,content)

   editurl=request.route_url('editPage',pagename=name)

   return dict(content=content,name=name,edit=editurl)

@view_config(route_name='editPage',renderer='templates/editPage.mako')
def editPage(request):

    name=request.matchdict['pagename']
    page=DBSession.query(Page).filter_by(name=name).first()

    if 'form.submitted' in request.params:
        page.data = request.params['body']
        DBSession.add(page)
        return HTTPFound(request.route_url('viewPage',pagename=name))

    return dict(name=name,data=page.data,
            saveUrl=request.route_url('editPage',pagename=name))

@view_config(route_name='addPage',renderer='templates/addPage.mako')
def addPage(request):

    if 'form.submitted' in request.params:
        name=request.params['name']
        data=request.params['body']

        page=Page(name=name,data=data)
        DBSession.add(page)

        return HTTPFound(request.route_url('viewPage',pagename=name))

    name=request.matchdict['pagename']
    name=name[0] if name else ''

    return dict(name=name,
            saveUrl=request.route_url('addPage',pagename=''))

@view_config(route_name="game24",renderer="templates/24.mako")
def game24(request):
    return dict(solveUrl=request.route_url('solve24'))

import json
from .p24 import solve as s24

@view_config(route_name="solve24")
def solve24(request):

    res=s24(map(int,request.params.values()))
    return Response(res)
    
